<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head th:replace="fragments/head :: commonHead('添加项目成员')">
    <!-- 页面特定样式将由head.html中的通用头部替代 -->
</head>
<body class="bg-light">
    <div class="container py-5">
        <div class="row mb-4">
            <div class="col">
                <div class="d-flex justify-content-between align-items-center flex-wrap">
                    <div>
                        <h2 class="fw-bold text-primary mb-2">添加项目成员</h2>
                        <nav aria-label="breadcrumb">
                            <ol class="breadcrumb mb-0">
                                <li class="breadcrumb-item"><a th:href="@{/}" class="text-decoration-none">首页</a></li>
                                <li class="breadcrumb-item"><a th:href="@{/project/list}" class="text-decoration-none">项目列表</a></li>
                                <li class="breadcrumb-item"><a th:href="@{/project/{id}(id=${project.id})}" class="text-decoration-none">项目详情</a></li>
                                <li class="breadcrumb-item"><a th:href="@{/project-member/list/{id}(id=${project.id})}" class="text-decoration-none">项目成员</a></li>
                                <li class="breadcrumb-item active" aria-current="page">添加成员</li>
                            </ol>
                        </nav>
                    </div>
                </div>
            </div>
        </div>
        
        <div class="card border-0 shadow-sm rounded-3 overflow-hidden">
            <div class="card-header bg-white py-3">
                <h5 class="mb-0 text-primary">
                    <i class="fas fa-users me-2"></i>项目: <span th:text="${project.name}"></span>
                </h5>
            </div>
            <div class="card-body p-4">
                <form id="addMembersForm">
                    <div class="mb-4">
                        <label for="userIds" class="form-label">选择用户</label>
                        <select class="form-select select2" id="userIds" name="userIds" multiple required>
                            <option th:each="user : ${users}" 
                                    th:value="${user.id}" 
                                    th:text="${user.username} + ' (' + ${user.realName} + ')'"></option>
                        </select>
                        <div class="form-text">可以选择多个用户同时添加到项目中</div>
                    </div>
                    
                    <div class="mb-4">
                        <label for="role" class="form-label">选择角色</label>
                        <select class="form-select" id="role" name="role" required>
                            <option value="3">普通成员</option>
                            <option value="2">风险管理员</option>
                            <option value="1">项目经理</option>
                        </select>
                    </div>
                    
                    <div class="d-flex">
                        <button type="button" class="btn btn-primary me-2" onclick="addMembers()">
                            <i class="fas fa-plus me-1"></i> 添加成员
                        </button>
                        <a th:href="@{/project-member/list/{id}(id=${project.id})}" class="btn btn-secondary">
                            <i class="fas fa-arrow-left me-1"></i> 返回
                        </a>
                    </div>
                </form>
            </div>
        </div>
    </div>
    
    <footer class="footer mt-auto py-4 bg-dark text-white">
        <div class="container text-center">
            <span>© 2025 项目风险管理系统 | 版本 1.0</span>
        </div>
    </footer>
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <!-- Select2 JS -->
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script th:inline="javascript">
        document.addEventListener('DOMContentLoaded', function() {
            // 初始化Select2
            $('.select2').select2({
                theme: 'bootstrap-5',
                placeholder: '请选择用户',
                allowClear: true,
                width: '100%'
            });
        });
        
        // 批量添加成员
        function addMembers() {
            // 获取Select2选择的值
            const userIds = $('#userIds').val();
            const role = document.getElementById('role').value;
            const projectId = /*[[${project.id}]]*/ '1'; // 使用安全的注释形式来包含Thymeleaf表达式
            
            console.log('选择的用户IDs:', userIds);
            
            if (!userIds || userIds.length === 0) {
                alert('请选择至少一个用户');
                return;
            }
            
            // 使用FormData构建表单数据
            const formData = new FormData();
            formData.append('projectId', projectId);
            formData.append('role', role);
            
            // 添加多个用户ID，确保使用正确的参数名称
            if (Array.isArray(userIds)) {
                // 对于数组，需要为每个元素使用相同的键名
                userIds.forEach(userId => {
                    formData.append('userIds', userId);
                });
            } else {
                formData.append('userIds', userIds);
            }
            
            // 打印formData用于调试
            console.log('添加成员表单数据:');
            for (let pair of formData.entries()) {
                console.log(pair[0] + ': ' + pair[1]);
            }
            
            // 获取CSRF令牌
            const csrfHeader = document.querySelector('meta[name="_csrf_header"]').getAttribute('content');
            const csrfToken = document.querySelector('meta[name="_csrf"]').getAttribute('content');
            
            fetch('/risk-management/project-member/batch-add', {
                method: 'POST',
                headers: {
                    [csrfHeader]: csrfToken
                },
                body: formData
            })
            .then(response => {
                if (!response.ok) {
                    throw new Error('网络请求失败');
                }
                return response.json();
            })
            .then(result => {
                if (result.code === 200) {
                    alert('添加成员成功');
                    window.location.href = '/risk-management/project-member/list/' + projectId;
                } else {
                    alert('添加成员失败：' + result.message);
                }
            })
            .catch(error => {
                console.error('添加成员失败:', error);
                alert('添加成员请求失败，请稍后重试');
            });
        }
    </script>
</body>
</html> 